package com.sky.service.impl;

import com.alibaba.excel.EasyExcel;
import com.sky.dto.TurnoverReportDTO;
import com.sky.mapper.AllMapper;
import com.sky.mapper.OrderMapper;
import com.sky.result.Result;
import com.sky.service.ReporService;
import com.sky.service.WorkspaceService;
import com.sky.utils.DateUtil;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class ReporServicempl implements ReporService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
     private AllMapper allMapper;

    @Override
    public TurnoverReportVO turnoverStatistics(TurnoverReportDTO turnoverReportDTO) {
        //turnoverReportDTO.setEnd(turnoverReportDTO.getEnd().plusDays(1));

        //获取日期集合,每一天的日期
        LocalDate begin = turnoverReportDTO.getBegin();
        LocalDate end = turnoverReportDTO.getEnd();
        List<LocalDate> dateList = new ArrayList<>();
        for (; begin.isBefore(end.plusDays(1)); begin = begin.plusDays(1)) {
            dateList.add(begin);
        }

        //根据日期集合,在数据库中查询数据
        // List<ReportVO> reportVOList = orderMapper.turnoverStatistics(dateList);
        Map<LocalDate, Long> orderCountMap = orderMapper.turnoverStatistics(dateList)
                .stream()
                .collect(Collectors.toMap(ReportVO::getDate, ReportVO::getTurnover));


     /*   Map<LocalDate, Long> orderCountMap = new HashMap<>();
        reportVOList.forEach(order ->
                orderCountMap.put(order.getDate(), order.getTurnover())
        );*/
        //将数据拼接成前端要求的字符串格式
 /* reportVOList.forEach(report -> {
            sb.append(report.getDate() + ",");
            su.append(report.getTurnover() + ",");
        });*/
        //  String dishName = orderDetails.stream().map(OrderDetail::getName).collect(Collectors.joining(","));

        StringBuilder sb = new StringBuilder();
        StringBuilder su = new StringBuilder();

        dateList.forEach(dd -> {
            if (orderCountMap.get(dd) == null) {
                sb.append(dd + ",");
                su.append("0,");
            } else {
                sb.append(dd + ",");
                su.append(orderCountMap.get(dd) + ",");
            }
        });


        return TurnoverReportVO.builder()
                .turnoverList(su.toString())
                .dateList(sb.toString())
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(TurnoverReportDTO turnoverReportDTO) {
        //获取日期集合

        LocalDate begin = turnoverReportDTO.getBegin();
        LocalDate end = turnoverReportDTO.getEnd();
        List<LocalDate> date = new ArrayList<>();
        for (; begin.isBefore(end.plusDays(1)); begin = begin.plusDays(1)) {
            date.add(begin);
        }

        OrderReportVO orderReportVO = new OrderReportVO();
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ss");
//订单总数

        Integer totalOrderNum = orderMapper.totalOrderNum(date);
        if (totalOrderNum == null) {
            orderReportVO.setTotalOrderCount(0);
        } else {
            orderReportVO.setTotalOrderCount(totalOrderNum);
        }

//每日订单数
        // List<ReportVO> orderCountList = orderMapper.orderCountList(date);
        Map<LocalDate, Long> orderDayMap = orderMapper.orderCountList(date)
                .stream()
                .collect(Collectors.toMap(ReportVO::getDate, ReportVO::getTurnover));

     /* //  Map<LocalDate, Long> orderDayMap = new HashMap<>();
        orderCountList.forEach(order ->
                orderDayMap.put(order.getDate(), order.getTurnover())
        );*/

//有效订单数

        Integer validOrderCount = orderMapper.validOrderCount(date);
        //orderReportVO.setValidOrderCount(validOrderCount);
        if (validOrderCount == null) {
            orderReportVO.setValidOrderCount(0);
        } else {
            orderReportVO.setValidOrderCount(validOrderCount);
        }
//订单率
        Double orderCompletionRate = 0.0;
        if (totalOrderNum != null) {
            orderCompletionRate = (double) validOrderCount / totalOrderNum;
        }
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
//每日有效订单数
        Map<LocalDate, Long> validOrderCountMap = orderMapper.validOrderCountList(date)
                .stream()
                .collect(Collectors.toMap(ReportVO::getDate, ReportVO::getTurnover));

       /* Map<LocalDate, Long> validOrderCountMap = new HashMap<>();
        validOrderCountList.forEach(validOrder ->
                validOrderCountMap.put(validOrder.getDate(), validOrder.getTurnover())
        );*/
        StringBuilder sb = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        StringBuilder sb3 = new StringBuilder();
        date.forEach(dd -> {
            sb.append(dd + ",");
            if (orderDayMap.get(dd) == null) {
                sb2.append("0,");
            } else {
                sb2.append(orderDayMap.get(dd) + ",");
            }
            if (validOrderCountMap.get(dd) == null) {
                sb3.append("0,");
            } else {
                sb3.append(validOrderCountMap.get(dd) + ",");
            }
        });
        orderReportVO.setOrderCountList(sb2.toString());
        orderReportVO.setValidOrderCountList(sb3.toString());
        orderReportVO.setDateList(sb.toString());


        return orderReportVO;

    }

    @Override
    public SalesTop10ReportVO top(TurnoverReportDTO turnoverReportDTO) {
        turnoverReportDTO.setEnd(turnoverReportDTO.getEnd().plusDays(1));

        StringBuilder sb = new StringBuilder();
        StringBuilder su = new StringBuilder();
        List<DishTopVO> top = orderMapper.top(turnoverReportDTO);
        if (top.size() == 0 || top == null) {
            return new SalesTop10ReportVO("null", "0");
        } else {
            top.subList(0, 10)
                    .forEach(to -> {
                        sb.append(to.getName() + ",");
                        su.append(to.getTurnover() + ",");
                    });

            return SalesTop10ReportVO.builder()
                    .nameList(sb.toString())
                    .numberList(su.toString()).build();

        }
        /*top.subList(0, 10)
                .forEach(to -> {

                    sb.append(to.getName() + ",");
                    su.append(to.getTurnover() + ",");
                });*/

    }

    @Override
    public UserReportVO userStatistics(TurnoverReportDTO turnoverReportDTO) {
        LocalDate begin = turnoverReportDTO.getBegin();
        LocalDate end = turnoverReportDTO.getEnd();

        Long allUser = orderMapper.seleAlltUser(begin);


        List<LocalDate> dateList = new ArrayList<>();
        for (; begin.isBefore(end.plusDays(1)); begin = begin.plusDays(1)) {
            dateList.add(begin);
        }

        Map<LocalDate, Long> newUserList = orderMapper.seletUser(dateList).stream()
                .collect(Collectors.toMap(ReportVO::getDate, ReportVO::getTurnover));

        StringBuilder sb = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        StringBuilder sb3 = new StringBuilder();
        // Long allUser = orderMapper.seleAlltUser(begin);
        if (allUser == null) {
            allUser = Long.valueOf(0);
        }
        //sb3.append(allUser+",");
        for (LocalDate dd : dateList) {
            if (newUserList.get(dd) == null) {
                sb2.append("0,");
                //sb3.append(allUser+",");
            } else {
                Long aLong = newUserList.get(dd);
                allUser += aLong;
                sb2.append(aLong + ",");
            }
            sb.append(dd + ",");
            sb3.append(allUser + ",");
        }

        return UserReportVO.builder()
                .dateList(sb.toString())
                .totalUserList(sb3.toString())
                .newUserList(sb2.toString()).build();
    }

    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = allMapper.getBusinessDataForDate(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = allMapper.getBusinessDataForDate(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }




     /*   String begin = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String end = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//获取日期列表
        List<String> dateList = DateUtil.getDateList(begin, end);
//获取用户总量和新增用户；

        TurnoverReportDTO build = TurnoverReportDTO.builder().begin(LocalDate.parse(begin)).end(LocalDate.parse(end)).build();


        UserReportVO userReportVO = userStatistics(build);
        String[] newUserList = userReportVO.getNewUserList().split(",");
        String[] totalUserList = userReportVO.getTotalUserList().split(",");
//获取营业额
        TurnoverReportVO turnoverReportVO = turnoverStatistics(build);
        String[] turnOverList = turnoverReportVO.getTurnoverList().split(",");
//获取有效订单和总订单
        OrderReportVO orderReportVO = ordersStatistics(build);
        String[] orderCountList = orderReportVO.getOrderCountList().split(",");
        String[] validOrderCountList = orderReportVO.getValidOrderCountList().split(",");
        List<ExcelReport> list = new ArrayList<>();
        for (int i = 0; i < dateList.size(); i++) {
            ExcelReport excelReport = new ExcelReport();
            excelReport.setDate(dateList.get(i));
            excelReport.setNewUser(newUserList[i]);
            excelReport.setTotalUser(totalUserList[i]);
            excelReport.setTotalOrder(orderCountList[i]);
            excelReport.setValidOrder(validOrderCountList[i]);
            excelReport.setTurnOver(turnOverList[i]);
            list.add(excelReport);
        }

        String fileName = System.currentTimeMillis()+".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        try {
            EasyExcel.write(response.getOutputStream(), ExcelReport.class).sheet("数据报表").doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
*/
    }
}
